<script>
import YmFormField from './YmFormField'
import * as Element from '@/store/elements'
import * as Ui from '@/store/elementui'

/**
 * props { fields: array<filed>, value }
 *
 */
export default {
  name: 'YmFormFields',
  functional: true,
  render (h, context) {
    const { props, listeners } = context

    if (!props[Ui.FIELDS]) {
      console.log('render fields error', props)
      return []
    }

    // 表单值对象
    const obj = {
      ...props.value
    }

    const setter = (name) => {
      return (v) => {
        if (name) {
          obj[name] = v
          listeners.input && listeners.input(obj)
        }
      }
    }

    const fnValue = (field) => {
      if (field[Element.NAME] !== undefined && obj[field[Element.NAME]] !== undefined) {
        return obj[field[Element.NAME]]
      }
      return Ui.WIDGETS.getDefaultValue(field)
    }

    const onClick = listeners.click

    const fields = props[Ui.FIELDS].map((field, index) => {
      let name = field[Element.NAME] ? field[Element.NAME] : undefined

      // 处理disable
      let disabled = field.disabled
      if (!disabled && field.when && field.when.name) {
        const v = obj[field.when.name]
        disabled = Array.isArray(field.when.value) ? field.when.value.includes(v) : field.when.value === v
      }
      if (disabled && name && obj[name] !== undefined) delete obj[name]

      //
      let labelPosition = field.labelPosition || props.labelPosition

      let value = fnValue(field)

      let span = field[Ui.COL] || 24

      let vNode = h(YmFormField, {
        props: {
          value,
          ...field,
          disabled,
          labelPosition
        },
        on: {
          ...listeners,
          input: setter(name),
          change: setter(name)
        }
      })

      return h('el-col', {
        props: {
          span
        },
        nativeOn: {
          click: () => {
            onClick && onClick(field, index)
          }
        }
      }, [vNode])
    })

    // console.log(fields)

    return h('el-row', {
        props: {
          gutter: 20
        }
      }, fields)
  }
}
</script>
